import maya.cmds as mc
import maya.mel as mm
class LZ_blendshape_command():
    def __init__(self):
        pass
        
        
    def AppendTarget(self , targets = [''] , BlendMesh = '',blendshape_node = ''):
        seleObject = targets
        textResult01=''
        textResult02=''
        textResult=''
        
        blendhspae_is_inscence = mc.objExists(blendshape_node)
        if blendhspae_is_inscence == 1 :
            blendshape_exists = self.list_BlendNode( mesh = BlendMesh )
            #print(blendshape_exists)
            #print(blendshape_exists)
            if blendshape_exists != None:
            
                if seleObject==None:
                    pass
                else:
                    BaseMesh= BlendMesh 
                    feedback01=1
                    feedback02=1
                    blendshapeNode = blendshape_exists
                    for so in seleObject:
                        
                        if so in self.listAllTarget(blendshapeNode):
                            textResult02='there is some meshs has already existed in '+str(blendshapeNode)
                            feedback02=0
                        
                            
                                
                        else:
                            if so!=BaseMesh:
                
                                lastIndex=self.findLastIndex(blendshapeNode)
                                
                                mc.blendShape(blendshapeNode,e=True,tc=True,t=[BaseMesh,lastIndex,so,1])
                                
                
                                
                            else:
                                
                                #mc.textField('currentBlendWeightList',e=True,bgc=[0,0.65,0],text='please select one mesh which name is not '+str(BaseMesh)+' at last')
                                feedback01=0
                                #mc.select(so)
                                #pass 
                    if feedback01==1:
                        
                        if feedback02==1:
                            textResult=str(seleObject)+'has appended to the '+str(blendshapeNode)+str(lastIndex)
                            #backGroundColor=[0,0.65,0]
                        else:
                            textResult=textResult01 + textResult02 + ',the others continued'
                            #backGroundColor=[0.9,0,0.5]
                    else:
                        textResult01='there is a mesh selected named '+str(BaseMesh)
                        textResult=textResult01 + textResult02 + ',the others continued'
                        #backGroundColor=[0.9,0,0.5]
                
                
                    #mc.textField('currentBlendWeightList',e=True,bgc=backGroundColor,text=textResult)   
                    #print( textResult )
            else:
                print( blendshape_node+ 'is not a input node on the mesh of '+ BlendMesh)
        else:
            mc.blendShape( targets , BlendMesh ,n= blendshape_node , frontOfChain =True)
                
                
    '''     


    '''    
        
    def list_BlendNode(self , mesh = '' ):
        
        blendMember = 0
        blendShapes=[]
        input = mc.listHistory(mesh)   
        for ip in input:
            if mc.nodeType(ip) == 'blendShape':
                blendMember = blendMember + 1
                blendShapes.append(ip)
            else:
                pass
        
        if blendMember >= 1:
            return blendShapes[0]
        elif blendMember == 0:
             return None
    
    
    
    def listAllTarget(self,blendShape_node):
        
        blendshapeNode=blendShape_node
        getWeightName=self.getWeightName(blendshapeNode)
        
        return getWeightName
    '''
    getTargetInputTargetItem ( string , int )
    
    get the value like 6000    get (int)
    '''
    def getTargetInputTargetItem(self,blendShapeNode,inputTargetNum):
        InputTargetItem=mc.getAttr(str(blendShapeNode)+'.inputTarget[0].inputTargetGroup['+str(inputTargetNum)+'].inputTargetItem' ,mi=True)
        return InputTargetItem
    '''
    getWeightIndex(string,string)
    get the index of the weight input    get (int)
    
    ''' 
    def getWeightIndex(self,blendShapeNode,target):
        aliases=mc.aliasAttr(blendShapeNode,q=True)

        for i in range(len(aliases)):
            if target==aliases[i]:
                index=(aliases[i+1].split('[')[1]).split(']')[0]
                
                index=int(index)+1
                break
            else:
                index='something mistake has Occurred'

        return index
    '''
    getWeightName(string)
    get the weight names in the blendShape input
    
    '''
    def getWeightName(self,blendShapeNode):
        aliases=mc.aliasAttr(blendShapeNode,q=True)
        blendshapeTarget=[]
        for bt in range(len(aliases)/2):
            blendshapeTarget.append(aliases[bt*2])
        return(blendshapeTarget)
        
    def findLastIndex(self,blendShapeNode):
        aliases=mc.aliasAttr(blendShapeNode,q=True)
        index=1
        for i in range(len(aliases)/2):
            currentIndex=int((aliases[i*2+1].split('[')[1]).split(']')[0])+1
            if currentIndex>index:
                index=currentIndex
        return(index)
        #i =len(aliases)/2-1
        #index=int((aliases[i*2+1].split('[')[1]).split(']')[0])+1
        #return(int(index))
        #
    def getBlendshapeNode(self,obj=''):
        blendNode=''
        for leave in range(6):
            
        
            nodeHistory=mc.listHistory(obj,lv=leave+1)

            for i in nodeHistory:
                #print (i)
                if mc.nodeType(i)=='blendShape':
                    blendNode=i
            if blendNode!='':
                break
        return(blendNode)
    def renameTargetWeightName(self,newName,blendshapenode,targetWeight):
        
        mc.aliasAttr(newName,str(blendshapenode)+'.'+str(targetWeight))
    
    '''
    
    RebuildTargetConnect(string,string,string,int)
    
    reconnect the target and blendShape weight
    
    '''
    def RebuildTargetConnect(self,OriMesh,TargetMesh,blendshape,TargetIndex):

        getOriMeshShapes=mc.listRelatives(OriMesh,s=True)
        getTargetMeshShapes=mc.listRelatives(TargetMesh,s=True)

        for gom in getOriMeshShapes:
            if 'Orig' in gom:
                getOriMeshShapes.remove(gom)
                
        for gtm in getTargetMeshShapes:
            if 'Orig' in gtm:
            
                getTargetMeshShapes.remove(gtm)
            
        if len(getOriMeshShapes)==len(getTargetMeshShapes):

            for i in range(len(getOriMeshShapes)):
                if 'Orig' in getTargetMeshShapes[i]:
                    pass
                else:
                    inputTargetNum=int(TargetIndex)-1
                    InputTargetItemNum=self.getTargetInputTargetItem(blendshape,inputTargetNum)
                    connecteAttr=str(blendshape)+'.inputTarget['+str(i)+'].inputTargetGroup['+str(inputTargetNum)+'].inputTargetItem['+str(InputTargetItemNum[0])+'].inputGeomTarget'
                    sourceInput=str(getTargetMeshShapes[i])+'.worldMesh[0]'
                    
                    sourceMesh=mc.listConnections(connecteAttr,s=True)
                    if sourceMesh!=None:
                        sourceMeshShapes=mc.listRelatives(sourceMesh,s=True)
                        mc.disconnectAttr(str(sourceMeshShapes[i])+'.worldMesh[0]', connecteAttr)

                    mc.connectAttr(sourceInput,connecteAttr)
                    
    '''
    selectConectInputObj(string,sting)
    select the object which is the target of blendShape

    ''' 
    def selectConectInputObj(self,blendShapeNode,getWeightName):
        inputTargetNum=self.getWeightIndex(blendShapeNode,getWeightName)-1
        InputTargetItemNum=self.getTargetInputTargetItem(blendShapeNode,inputTargetNum)

        conneSouce=mc.listConnections(str(blendShapeNode)+'.inputTarget[0].inputTargetGroup['+str(inputTargetNum)+'].inputTargetItem['+str(InputTargetItemNum[0])+'].inputGeomTarget',s=True)
        if conneSouce!=None:
            return conneSouce[0]
            
        else:
            return 0
            
    def setAllTargetWeight2Off(self,blendshape):
        AllTargets=self.getWeightName(blendshape)
        for at in AllTargets:
            mc.setAttr(str(blendshape)+'.'+str(at),0)
    def setTargetWeight2On(self,blendshape,target):
        mc.setAttr(str(blendshape)+'.'+str(target),1)
    def getTargetInputMesh(self,OriMesh,blendshape,target):
        self.setAllTargetWeight2Off(blendshape)
        self.setTargetWeight2On(blendshape,target)
        TargetIndex=self.getWeightIndex(blendshape,target)
        mc.duplicate(OriMesh,n=target)
        
        self.RebuildTargetConnect(OriMesh,target,blendshape,TargetIndex)
        
        
        
    ## =================================================================================
    ##    wrap  deformer menager
    
    ##----------------------------------------------------------------------------------
        
        
    def LZ_WrapDeformer(self,originalObj, shapeToCopy , newObj) :
        
    
        #//unlock attributes if originalMesh is skinned for example
        
        OriginalObjTX = originalObj + ".tx"
        mc.setAttr (OriginalObjTX, lock = 0 )
    
        OriginalObjTY = originalObj + ".ty"
        mc.setAttr (OriginalObjTY, lock = 0 )
    
        OriginalObjTZ = originalObj + ".tz"
        mc.setAttr (OriginalObjTZ, lock = 0)
    
        OriginalObjRX = originalObj + ".rx"
        mc.setAttr (OriginalObjRX ,lock = 0)
    
        OriginalObjRY = originalObj + ".ry"
        mc.setAttr (OriginalObjRY, lock = 0 )
    
        OriginalObjRZ = originalObj + ".rz"
        mc.setAttr (OriginalObjRZ, lock = 0 )
    
        OriginalObjSX = originalObj + ".sx"
        mc.setAttr (OriginalObjSX, lock = 0 )
    
        OriginalObjSY = originalObj + ".sy"
        mc.setAttr (OriginalObjSY, lock = 0 )
    
        OriginalObjSZ = originalObj + ".sz"
        mc.setAttr (OriginalObjSZ, lock = 0)
        
        
        '''
        
        ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
        
        
        '''
        wrapObj = shapeToCopy + "suffTemp"
        mc.duplicate (originalObj, rr = 1, n = "blendObj")
        mc.duplicate ( newObj , rr = 1, n = "tempName")
    
        mc.rename("tempName", wrapObj) 
        
        for  objD in [ "blendObj", wrapObj ]:
            for attr in  ['.tx','.ty','.tz','.rx','.ry','.rz']:
                mc.setAttr( str(objD)  + attr , 0 )
        
        
        
        
        
        blendshapeToWrap = originalObj + "_blendShapeToWarp"
        mc.blendShape (shapeToCopy, "blendObj", frontOfChain = 1, n = blendshapeToWrap)
        
        mc.select ( wrapObj , "blendObj",  r=1) 
        
        wrapName = mm.eval('doWrapArgList "6" { "1","0","1", "2", "1", "1", "0" };')[0]
        
        #valeur blend shape mise 1
        blendShapeAttr = str(blendshapeToWrap)+"." + shapeToCopy
        mc.setAttr(blendShapeAttr, 1)
        
        #delete history de l'objet copi
        mc.select (wrapObj, r = 1)
        mc.DeleteHistory
        mc.delete (ch = 1)
        
        #suppression des deux objets temporaires
        mc.delete ('blendObjBase', 'blendObj')
        
        newName = originalObj + '_wrap'
        mc.rename( wrapObj , newName)
        
        return newName